home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / pine3.07 / c-client / os_aix.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-05-14  |  16.4 KB  |  576 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- ANSI BSD Unix version
  3.  *
  4.  * Author:    Mark Crispin
  5.  *        Networks and Distributed Computing
  6.  *        Computing & Communications
  7.  *        University of Washington
  8.  *        Administration Building, AG-44
  9.  *        Seattle, WA  98195
  10.  *        Internet: MRC@CAC.Washington.EDU
  11.  *
  12.  * Date:    1 August 1988
  13.  * Last Edited:    14 May 1992
  14.  *
  15.  * Copyright 1992 by the University of Washington.
  16.  *
  17.  *  Permission to use, copy, modify, and distribute this software and its
  18.  * documentation for any purpose and without fee is hereby granted, provided
  19.  * that the above copyright notice appears in all copies and that both the
  20.  * above copyright notice and this permission notice appear in supporting
  21.  * documentation, and that the name of the University of Washington not be
  22.  * used in advertising or publicity pertaining to distribution of the software
  23.  * without specific, written prior permission.  This software is made available
  24.  * "as is", and
  25.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  26.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  27.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  28.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  29.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  30.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  31.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  32.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  33.  *
  34.  */
  35.  
  36. /* TCP input buffer */
  37.  
  38. #define BUFLEN 8192
  39.  
  40.  
  41. /* TCP I/O stream (must be before osdep.h is included) */
  42.  
  43. #define TCPSTREAM struct tcp_stream
  44. TCPSTREAM {
  45.   char *host;            /* host name */
  46.   char *localhost;        /* local host name */
  47.   int tcpsi;            /* input socket */
  48.   int tcpso;            /* output socket */
  49.   int ictr;            /* input counter */
  50.   char *iptr;            /* input pointer */
  51.   char ibuf[BUFLEN];        /* input buffer */
  52. };
  53.  
  54.  
  55. #include <sys/types.h>
  56. #include <sys/time.h>
  57. #include <sys/socket.h>
  58. #include <netinet/in.h>
  59. #include <netdb.h>
  60. #include <ctype.h>
  61. #include <errno.h>
  62. extern int errno;        /* just in case */
  63. #include <pwd.h>
  64. #include <syslog.h>
  65. #include "osdep.h"
  66. #include "mail.h"
  67. #include "misc.h"
  68. extern char *crypt();
  69.  
  70. extern long timezone;
  71. extern int daylight;
  72. extern char *tzname[2];
  73.  
  74. extern int sys_nerr;
  75. extern char *sys_errlist[];
  76.  
  77. /* Write current time in RFC 822 format
  78.  * Accepts: destination string
  79.  */
  80.  
  81. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  82. char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  83.         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  84.  
  85. void rfc822_date (char *date)
  86. {
  87.   int zone;
  88.   struct tm *t;
  89.   struct timeval tv;
  90.   struct timezone tz;
  91.   gettimeofday (&tv,&tz);    /* get time and timezone poop */
  92.   t = localtime (&tv.tv_sec);    /* convert to individual items */
  93.   tzset ();            /* get timezone from TZ environment stuff */
  94.   zone = -timezone/60;
  95.                 /* and output it */
  96.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+02d%02d (%s)",
  97.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  98.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,
  99.        tzname[daylight ? t->tm_isdst : 0]);
  100. }
  101.  
  102. /* Get a block of free storage
  103.  * Accepts: size of desired block
  104.  * Returns: free storage block
  105.  */
  106.  
  107. void *fs_get (size_t size)
  108. {
  109.   void *block = malloc (size);
  110.   if (!block) fatal ("Out of free storage");
  111.   return (block);
  112. }
  113.  
  114.  
  115. /* Resize a block of free storage
  116.  * Accepts: ** pointer to current block
  117.  *        new size
  118.  */
  119.  
  120. void fs_resize (void **block,size_t size)
  121. {
  122.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  123. }
  124.  
  125.  
  126. /* Return a block of free storage
  127.  * Accepts: ** pointer to free storage block
  128.  */
  129.  
  130. void fs_give (void **block)
  131. {
  132.   free (*block);
  133.   *block = NIL;
  134. }
  135.  
  136.  
  137. /* Report a fatal error
  138.  * Accepts: string to output
  139.  */
  140.  
  141. void fatal (char *string)
  142. {
  143.   mm_fatal (string);        /* pass up the string */
  144.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  145.   abort ();            /* die horribly */
  146. }
  147.  
  148. /* Copy string with CRLF newlines
  149.  * Accepts: destination string
  150.  *        pointer to size of destination string
  151.  *        source string
  152.  *        length of source string
  153.  */
  154.  
  155. char *strcrlfcpy (char **dst,unsigned long *dstl,char *src,unsigned long srcl)
  156. {
  157.   long i,j;
  158.   char *d = src;
  159.                 /* count number of LF's in source string(s) */
  160.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  161.   if (i > *dstl) {        /* resize if not enough space */
  162.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  163.     *dst = (char *) fs_get ((*dstl = i) + 1);
  164.   }
  165.   d = *dst;            /* destination string */
  166.                 /* copy strings, inserting CR's before LF's */
  167.   while (srcl--) switch (*src) {
  168.   case '\015':            /* unlikely carriage return */
  169.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  170.     if (srcl && *src == '\012') {
  171.       *d++ = *src++;
  172.       srcl--;
  173.     }
  174.     break;
  175.   case '\012':            /* line feed? */
  176.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  177.   default:            /* ordinary chararacter */
  178.     *d++ = *src++;        /* just copy character */
  179.     break;
  180.   }
  181.   *d = '\0';            /* tie off destination */
  182.   return *dst;            /* return destination */
  183. }
  184.  
  185.  
  186. /* Length of string after strcrlflen applied
  187.  * Accepts: source string
  188.  *        length of source string
  189.  */
  190.  
  191. unsigned long strcrlflen (char *src,unsigned long srcl)
  192. {
  193.   long i = srcl;        /* look for LF's */
  194.   while (srcl--) switch (*src++) {
  195.   case '\015':            /* unlikely carriage return */
  196.     if (srcl && *src == '\012') { src++; srcl--; }
  197.     break;
  198.   case '\012':            /* line feed? */
  199.     i++;
  200.   default:            /* ordinary chararacter */
  201.     break;
  202.   }
  203.   return i;
  204. }
  205.  
  206. /* Server log in
  207.  * Accepts: user name string
  208.  *        password string
  209.  *        optional place to return home directory
  210.  * Returns: T if password validated, NIL otherwise
  211.  */
  212.  
  213. long server_login (char *user,char *pass,char **home)
  214. {
  215.   struct passwd *pw = getpwnam (lcase (user));
  216.                 /* no entry for this user or root */
  217.   if (!(pw && pw->pw_uid)) return NIL;
  218.                 /* validate password */
  219.   if (strcmp (pw->pw_passwd,(char *) crypt (pass,pw->pw_passwd))) return NIL;
  220.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  221.   setuid (pw->pw_uid);
  222.                 /* note home directory */
  223.   if (home) *home = cpystr (pw->pw_dir);
  224.   return T;
  225. }
  226.   
  227. /* TCP/IP open
  228.  * Accepts: host name
  229.  *        contact port number
  230.  * Returns: TCP/IP stream if success else NIL
  231.  */
  232.  
  233. TCPSTREAM *tcp_open (char *host,int port)
  234. {
  235.   TCPSTREAM *stream = NIL;
  236.   int sock;
  237.   char *s;
  238.   struct sockaddr_in sin;
  239.   struct hostent *host_name;
  240.   char hostname[MAILTMPLEN];
  241.   char tmp[MAILTMPLEN];
  242.   /* The domain literal form is used (rather than simply the dotted decimal
  243.      as with other Unix programs) because it has to be a valid "host name"
  244.      in mailsystem terminology. */
  245.                 /* look like domain literal? */
  246.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  247.     strcpy (hostname,host+1);    /* yes, copy number part */
  248.     hostname[(strlen (hostname))-1] = '\0';
  249.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  250.       sin.sin_family = AF_INET;    /* family is always Internet */
  251.       strcpy (hostname,host);    /* hostname is user's argument */
  252.     }
  253.     else {
  254.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  255.       mm_log (tmp,ERROR);
  256.       return NIL;
  257.     }
  258.   }
  259.  
  260.   else {            /* lookup host name, note that brain-dead Unix
  261.                    requires lowercase! */
  262.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  263.     if ((host_name = gethostbyname (lcase (hostname)))) {
  264.                 /* copy address type */
  265.       sin.sin_family = host_name->h_addrtype;
  266.                 /* copy host name */
  267.       strcpy (hostname,host_name->h_name);
  268.                 /* copy host addresses */
  269.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  270.     }
  271.     else {
  272.       switch (h_errno) {
  273.     case HOST_NOT_FOUND:    /* authoritative error */
  274.       s = "No such host as %.80s";
  275.       break;
  276.     case TRY_AGAIN:        /* non-authoritative error */
  277.       s = "Transient error for host %.80s, try again";
  278.       break;
  279.     case NO_RECOVERY:    /* non-recoverable errors */
  280.       s = "Non-recoverable error looking up host %.80s";
  281.       break;
  282.     case NO_DATA:        /* no data record of requested type */
  283.       s = "No IP address known for host %.80s";
  284.       break;
  285.     default:
  286.       s = "Unknown error for host %.80s";
  287.       break;
  288.       }
  289.       sprintf (tmp,s,host);
  290.       mm_log (tmp,ERROR);
  291.       return NIL;
  292.     }
  293.   }
  294.  
  295.                 /* copy port number in network format */
  296.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  297.                 /* get a TCP stream */
  298.   if ((sock = socket (sin.sin_family,SOCK_STREAM,0)) < 0) {
  299.     sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
  300.     mm_log (tmp,ERROR);
  301.     return NIL;
  302.   }
  303.                 /* open connection */
  304.   if (connect (sock,(struct sockaddr *)&sin,sizeof (sin)) < 0) {
  305.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  306.          strerror (errno));
  307.     mm_log (tmp,ERROR);
  308.     return NIL;
  309.   }
  310.                 /* create TCP/IP stream */
  311.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  312.                 /* copy official host name */
  313.   stream->host = cpystr (hostname);
  314.                 /* get local name */
  315.   gethostname (tmp,MAILTMPLEN-1);
  316.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  317.                   host_name->h_name : tmp);
  318.                 /* init sockets */
  319.   stream->tcpsi = stream->tcpso = sock;
  320.   stream->ictr = 0;        /* init input counter */
  321.   return stream;        /* return success */
  322. }
  323.   
  324. /* TCP/IP authenticated open
  325.  * Accepts: host name
  326.  *        service name
  327.  * Returns: TCP/IP stream if success else NIL
  328.  */
  329.  
  330. TCPSTREAM *tcp_aopen (char *host,char *service)
  331. {
  332.   TCPSTREAM *stream = NIL;
  333.   struct hostent *host_name;
  334.   char hostname[MAILTMPLEN];
  335.   int i;
  336.   int pipei[2],pipeo[2];
  337.   /* The domain literal form is used (rather than simply the dotted decimal
  338.      as with other Unix programs) because it has to be a valid "host name"
  339.      in mailsystem terminology. */
  340.                 /* look like domain literal? */
  341.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  342.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  343.     hostname[i-1] = '\0';
  344.   }
  345.                 /* note that Unix requires lowercase! */
  346.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  347.     strcpy (hostname,host_name->h_name);
  348.                 /* make command pipes */
  349.   if (pipe (pipei) < 0) return NIL;
  350.   if (pipe (pipeo) < 0) {
  351.     close (pipei[0]); close (pipei[1]);
  352.     return NIL;
  353.   }
  354.   if ((i = fork ()) < 0) {    /* make inferior process */
  355.     close (pipei[0]); close (pipei[1]);
  356.     close (pipeo[0]); close (pipeo[1]);
  357.     return NIL;
  358.   }
  359.   if (i) {            /* parent? */
  360.     close (pipei[1]);        /* close child's side of the pipes */
  361.     close (pipeo[0]);
  362.   }
  363.   else {            /* child */
  364.     dup2 (pipei[1],1);        /* parent's input is my output */
  365.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  366.     close (pipei[0]); close (pipei[1]);
  367.     dup2 (pipeo[0],0);        /* parent's output is my input */
  368.     close (pipeo[0]); close (pipeo[1]);
  369.                 /* now run it */
  370.     execl ("/usr/ucb/rsh","rsh",hostname,"exec",service,0);
  371.     _exit (1);            /* spazzed */
  372.   }
  373.  
  374.                 /* create TCP/IP stream */
  375.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  376.                 /* copy official host name */
  377.   stream->host = cpystr (hostname);
  378.                 /* get local name */
  379.   gethostname (hostname,MAILTMPLEN-1);
  380.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  381.                   host_name->h_name : hostname);
  382.   stream->tcpsi = pipei[0];    /* init sockets */
  383.   stream->tcpso = pipeo[1];
  384.   stream->ictr = 0;        /* init input counter */
  385.   return stream;        /* return success */
  386. }
  387.  
  388. /* TCP/IP receive line
  389.  * Accepts: TCP/IP stream
  390.  * Returns: text line string or NIL if failure
  391.  */
  392.  
  393. char *tcp_getline (TCPSTREAM *stream)
  394. {
  395.   int n,m;
  396.   char *st;
  397.   char *ret;
  398.   char *stp;
  399.   char tmp[2];
  400.   fd_set fds;
  401.   FD_ZERO (&fds);        /* initialize selection vector */
  402.   if (stream->tcpsi < 0) return NIL;
  403.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  404.     FD_SET (stream->tcpsi,&fds);/* set bit in selection vector */
  405.                 /* block and read */
  406.     if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  407.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  408.       close (stream->tcpsi);    /* nuke the socket */
  409.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  410.       stream->tcpsi = stream->tcpso = -1;
  411.       return NIL;
  412.     }
  413.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  414.   }
  415.   st = stream->iptr;        /* save start of string */
  416.   n = 0;            /* init string count */
  417.   while (stream->ictr--) {    /* look for end of line */
  418.                 /* saw the trailing CR? */
  419.     if (stream->iptr++[0] == '\015') {
  420.       ret = (char *) fs_get (n+1);
  421.       memcpy (ret,st,n);    /* copy into a free storage string */
  422.       ret[n] = '\0';        /* tie off string with null */
  423.                 /* eat the line feed */
  424.       tcp_getbuffer (stream,1,tmp);
  425.       return ret;        /* return it to caller */
  426.     }
  427.     ++n;            /* else count and try next character */
  428.   }
  429.   stp = (char *) fs_get (n);    /* copy first part of string */
  430.   memcpy (stp,st,n);
  431.                 /* recurse to get remainder */
  432.   if (st = tcp_getline (stream)) {
  433.                 /* build total string */
  434.     ret = (char *) fs_get (n+1+(m = strlen (st)));
  435.     memcpy (ret,stp,n);        /* copy first part */
  436.     memcpy (ret+n,st,m);    /* and second part */
  437.     ret[n+m] = '\0';        /* tie off string with null */
  438.     fs_give ((void **) &st);    /* flush partial string */
  439.     fs_give ((void **) &stp);    /* flush initial fragment */
  440.   }
  441.   else ret = stp;        /* return the fragment */
  442.   return ret;
  443. }
  444.  
  445. /* TCP/IP receive buffer
  446.  * Accepts: TCP/IP stream
  447.  *        size in bytes
  448.  *        buffer to read into
  449.  * Returns: T if success, NIL otherwise
  450.  */
  451.  
  452. long tcp_getbuffer (TCPSTREAM *stream,unsigned long size,char *buffer)
  453. {
  454.   unsigned long n;
  455.   char *bufptr = buffer;
  456.   fd_set fds;
  457.   FD_ZERO (&fds);        /* initialize selection vector */
  458.   if (stream->tcpsi < 0) return NIL;
  459.   while (size > 0) {        /* until request satisfied */
  460.     while (stream->ictr < 1) {    /* if nothing in the buffer */
  461.       FD_SET (stream->tcpsi,&fds);
  462.                 /* block and read */
  463.       if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  464.       ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  465.     close (stream->tcpsi);    /* nuke the socket */
  466.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  467.     stream->tcpsi = stream->tcpso = -1;
  468.     return NIL;
  469.       }
  470.                 /* point at TCP buffer */
  471.       stream->iptr = stream->ibuf;
  472.     }
  473.     n = min (size,stream->ictr);/* number of bytes to transfer */
  474.                 /* do the copy */
  475.     memcpy (bufptr,stream->iptr,n);
  476.     bufptr += n;        /* update pointer */
  477.     stream->iptr +=n;
  478.     size -= n;            /* update # of bytes to do */
  479.     stream->ictr -=n;
  480.   }
  481.   bufptr[0] = '\0';        /* tie off string */
  482.   return T;
  483. }
  484.  
  485. /* TCP/IP send string as record
  486.  * Accepts: TCP/IP stream
  487.  * Returns: T if success else NIL
  488.  */
  489.  
  490. long tcp_soutr (TCPSTREAM *stream,char *string)
  491. {
  492.   int i;
  493.   unsigned long size = strlen (string);
  494.   fd_set fds;
  495.   FD_ZERO (&fds);        /* initialize selection vector */
  496.   if (stream->tcpso < 0) return NIL;
  497.   while (size > 0) {        /* until request satisfied */
  498.     FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
  499.     if ((select (stream->tcpso+1,0,&fds,0,0) < 0) ||
  500.     ((i = write (stream->tcpso,string,size)) < 0)) {
  501.       puts (strerror (errno));
  502.       close (stream->tcpsi);    /* nuke the socket */
  503.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  504.       stream->tcpsi = stream->tcpso = -1;
  505.       return NIL;
  506.     }
  507.     size -= i;            /* count this size */
  508.     string += i;
  509.   }
  510.   return T;            /* all done */
  511. }
  512.  
  513.  
  514. /* TCP/IP close
  515.  * Accepts: TCP/IP stream
  516.  */
  517.  
  518. void tcp_close (TCPSTREAM *stream)
  519. {
  520.  
  521.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  522.     close (stream->tcpsi);    /* nuke the socket */
  523.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  524.     stream->tcpsi = stream->tcpso = -1;
  525.   }
  526.                 /* flush host names */
  527.   fs_give ((void **) &stream->host);
  528.   fs_give ((void **) &stream->localhost);
  529.   fs_give ((void **) &stream);    /* flush the stream */
  530. }
  531.  
  532. /* TCP/IP get host name
  533.  * Accepts: TCP/IP stream
  534.  * Returns: host name for this stream
  535.  */
  536.  
  537. char *tcp_host (TCPSTREAM *stream)
  538. {
  539.   return stream->host;        /* return host name */
  540. }
  541.  
  542.  
  543. /* TCP/IP get local host name
  544.  * Accepts: TCP/IP stream
  545.  * Returns: local host name
  546.  */
  547.  
  548. char *tcp_localhost (TCPSTREAM *stream)
  549. {
  550.   return stream->localhost;    /* return local host name */
  551. }
  552.  
  553. /* Copy memory block
  554.  * Accepts: destination pointer
  555.  *        source pointer
  556.  *        length
  557.  * Returns: destination pointer
  558.  */
  559.  
  560. char *memmove (char *s,char *ct,int n)
  561. {
  562.   bcopy (ct,s,n);        /* they should have this one */
  563.   return ct;
  564. }
  565.  
  566.  
  567. /* Return implementation-defined string corresponding to error
  568.  * Accepts: error number
  569.  * Returns: string for that error
  570.  */
  571.  
  572. char *strerror (int n)
  573. {
  574.   return (n >= 0 && n < sys_nerr) ? sys_errlist[n] : NIL;
  575. }
  576.